package com.ziyun.erp.web.modules.message.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.ziyun.erp.common.e.message.LaunchShapeEnum;
import com.ziyun.erp.common.e.message.MessageTypeEnum;
import com.ziyun.erp.common.e.service.ServiceTypeEnum;
import com.ziyun.erp.common.utils.JsonUtils;
import com.ziyun.erp.modules.message.entity.MessageEntity;
import com.ziyun.erp.modules.message.entity.MessageUserEntity;
import com.ziyun.erp.modules.message.service.MessageService;
import com.ziyun.erp.modules.message.service.MessageUserService;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * erp提示消息
 *
 * @author zh
 * @email 296588519@qq.com
 * @date 2018-08-13 14:22:52
 */
@RestController
@RequestMapping("message/message")
public class MessageController {
    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageUserService messageUserService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("message:message:list")
    public R list(Page<MessageEntity> page, @RequestParam Map<String, Object> params){
        // 获取当前用户id
        Long userId = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUserId();
        if(userId == Constant.SUPER_ADMIN){ //仅仅超级管理员可以查看所有消息
            page.setRecords((List<MessageEntity>) this.messageService.queryPage(params).getList());
        }else {
            params.put("userId", userId);
            this.messageUserService.queryUserMassagePage(page,params);
        }
        return R.ok().put("page", page);

    }

    @RequestMapping("/getEnum")
    @RequiresPermissions("message:message:list")
    public R getEnum(){
        //存放枚举类
        Map<String, List> mapEnum = new HashMap<>();
        mapEnum.put("messageTypeEnum", JsonUtils.enumToList(MessageTypeEnum.class));
        mapEnum.put("launchShapeEnum", JsonUtils.enumToList(LaunchShapeEnum.class));

        return R.ok().put("enum", mapEnum);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("message:message:info")
    public R info(@PathVariable("id") Integer id){
        MessageEntity message = messageService.selectById(id);

        return R.ok().put("message", message);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("message:message:save")
    public R save(@RequestBody MessageEntity message){
        // 获取当前用户id
        Long userId = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUserId();
        message.setCreateUser(userId.toString());
        message.setCreateDate(new Date());

        messageService.insertMessage(message);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("message:message:update")
    public R update(@RequestBody MessageEntity message){
        ValidatorUtils.validateEntity(message);
        messageService.updateAllColumnById(message);//全部更新
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("message:message:delete")
    public R delete(@RequestBody Integer[] ids){
        messageService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }


    @RequestMapping("/getMessage")
    public Map getMessage(@RequestParam(value="webCount", defaultValue="1")int webCount) throws InterruptedException {
        // 获取当前用户id
        Long userId = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUserId();
        List<MessageEntity> userMessageList = new ArrayList<MessageEntity>();
        while (true){ //保持连接
            System.out.println("线程开始工作");
            long startTime = System.currentTimeMillis();
            Map<String ,Object> params = new HashMap<String ,Object>();
            params.put("userId", userId);
            params.put("readFlag", 0);
            userMessageList = this.messageUserService.queryUserMessageList(params);
            if (userMessageList.size() >0 && webCount !=userMessageList.size()){
                break;
            }
            //todo 做睡眠 并且一定时间内释放连接
            System.out.println("线程开始休眠");
            Thread.sleep(180000);
            long endTime = System.currentTimeMillis();    //获取结束时间
            System.out.println("线程休眠时间：" + (endTime - startTime) + "ms");
        }
        Map rs = new HashMap();
        rs.put("count",userMessageList.size());
        rs.put("items", userMessageList);
        return rs;

    }

    /**
     * 标记已读
     * @param ids
     * @return
     */
    @RequestMapping("markupRead")
    public Map markupRead(@RequestBody Integer[] ids){
        // 获取当前用户id
        Long userId = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUserId();
        messageUserService.markupRead(ids, userId);

        return R.ok();
    }

}
